<template>
  <div class="recharge-container">
    <el-card class="package-select">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><ShoppingCart /></el-icon>
          <span>选择套餐</span>
          <div class="header-actions">
            <el-tooltip content="刷新套餐数据" placement="top">
              <el-button
                type="primary"
                :icon="Refresh" 
                circle 
                size="small"
                @click="refreshPackages"
                :loading="isLoadingPackages"
              ></el-button>
            </el-tooltip>
          </div>
        </div>
      </template>

      <div class="package-options">
        <!-- 套餐使用说明 -->
        <div class="package-usage-info">
          <el-alert
            type="info"
            :closable="false"
            show-icon
          >
            <div class="usage-info-content">
              <p>1个手机号码算1点数，规定时间用完，到期额度自动清零</p>
            </div>
          </el-alert>
        </div>

        <!-- 套餐类型选择 -->
        <div class="package-types">
          <el-radio-group v-model="selectedPackageType" @change="resetPackage">
            <el-radio-button 
              v-for="type in packageTypes" 
              :key="type" 
              :label="type"
            >
              {{ type }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 套餐加载中 -->
        <div v-if="isLoadingPackages" class="loading-packages">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>正在加载套餐信息...</span>
        </div>

        <!-- 套餐选择卡片 -->
        <div v-else class="packages-grid">
          <div
            v-for="(pkg, index) in packagesByType"
            :key="index"
            :class="['package-card', { active: selectedPackage && selectedPackage.price === pkg.price && selectedPackage.duration === pkg.duration }]"
            @click="selectPackage(pkg)"
          >
            <div v-if="pkg.isRecommended" class="recommended">推荐</div>
            <div class="package-header">
              <span class="title">{{ pkg.title }}</span>
              <span class="duration">{{ pkg.duration }}</span>
            </div>
            <div class="package-price">
              <span class="price-amount">¥{{ pkg.price }}</span>
              <span class="original-price">¥{{ Math.round(pkg.price * 1.2) }}</span>
            </div>
            <div class="package-details">
              <div class="detail-item">
                <el-icon class="detail-icon"><Present /></el-icon>
                <span>赠送 {{ pkg.points }} 点数</span>
              </div>
              <div class="features">
                <div class="feature-item">
                  <el-icon class="feature-icon"><Check /></el-icon>
                  <span>所有基础功能</span>
                </div>
                <div v-if="pkg.price > 1500" class="feature-item">
                  <el-icon class="feature-icon"><Check /></el-icon>
                  <span>优先队列处理</span>
                </div>
                <div v-if="pkg.duration.includes('365')" class="feature-item">
                  <el-icon class="feature-icon"><Check /></el-icon>
                  <span>年度专属权益</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 支付方式卡片 -->
    <el-card class="payment-method" v-if="selectedPackage">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Wallet /></el-icon>
          <span>选择支付方式</span>
        </div>
      </template>

      <div class="payment-methods">
        <div class="method-options">
          <div
            :class="['method-card', { active: paymentMethod === 1 }]"
            @click="selectPaymentMethod(1)"
          >
            <img src="@/assets/images/new/wechat-pay.svg" alt="微信支付" class="method-icon" />
            <span class="method-name">微信支付</span>
          </div>
          <div
            :class="['method-card', { active: paymentMethod === 2 }]"
            @click="selectPaymentMethod(2)"
          >
            <img src="@/assets/images/new/alipay.svg" alt="支付宝" class="method-icon" />
            <span class="method-name">支付宝</span>
          </div>
        </div>
      </div>

      <div class="payment-action">
        <el-button type="primary" size="large" @click="createPaymentOrder" :loading="isSubmitting">
          立即支付 ¥{{ selectedPackage ? selectedPackage.price : '0' }}
        </el-button>
      </div>
    </el-card>

    <!-- 支付弹窗 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="请扫码完成支付"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      class="payment-dialog"
    >
      <div class="payment-dialog-content">
        <div class="payment-info">
          <div class="order-details">
            <div class="order-info-item">
              <span class="label">订单号：</span>
            <span class="value">{{ currentOrderNo }}</span>
          </div>
            <div class="order-info-item">
              <span class="label">金额：</span>
              <span class="value price">¥{{ currentOrderAmount }}</span>
        </div>
            <div class="order-info-item">
              <span class="label">支付方式：</span>
              <span class="value">{{ paymentMethod === 1 ? '微信支付' : '支付宝' }}</span>
            </div>
            <div class="order-info-item payment-countdown">
          <el-icon><Timer /></el-icon>
          <span>请在 {{ paymentTimeRemaining }} 内完成支付</span>
        </div>
        </div>
          
          <div class="qrcode-container">
            <div v-if="paymentMethod === 1 && paymentQrCode" ref="qrcodeContainer" class="qrcode-image"></div>
            <div v-else-if="paymentMethod === 2 && paymentQrCode" ref="alipayFormContainer" class="alipay-form-container"></div>
            <div v-else class="loading-qrcode">
              <el-icon class="loading-icon" :size="40"><Loading /></el-icon>
              <span>正在生成支付信息...</span>
      </div>
          </div>
          
          <div class="payment-actions">
            <el-button type="primary" @click="checkPaymentStatus" :loading="checkingPayment">
              支付完成
            </el-button>
          <el-button @click="cancelPayment">取消支付</el-button>
        </div>
        </div>
      </div>
    </el-dialog>

    <!-- 支付结果弹窗 -->
    <el-dialog
      v-model="paymentResultDialogVisible"
      :title="paymentSuccess ? '支付成功' : '支付未完成'"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="payment-result">
        <div class="result-icon">
          <el-icon
            :class="[
              'status-icon',
              paymentSuccess ? 'success-icon' : 'waiting-icon'
            ]"
          >
            <component :is="paymentSuccess ? 'CircleCheck' : 'Warning'" />
          </el-icon>
        </div>
        <div class="result-message">
          {{ paymentSuccess ? '恭喜您，支付已成功！' : '未检测到支付完成，请确认是否已支付？' }}
        </div>
        <div class="result-detail" v-if="paymentSuccess">
          您的会员套餐已更新，感谢您的购买！
        </div>
        
        <!-- 支付成功时显示套餐详情 -->
        <div class="package-details-success" v-if="paymentSuccess">
          <div class="detail-item">
            <span class="detail-label">套餐类型</span>
            <span class="detail-value">{{ selectedPackageType || '标准套餐' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">套餐时长</span>
            <span class="detail-value">{{ selectedPackage?.duration || '未知' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">赠送点数</span>
            <span class="detail-value points">{{ selectedPackage?.points || 0 }} 点数</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">支付金额</span>
            <span class="detail-value price">¥{{ route.query.total_amount || selectedPackage?.price || 0 }}</span>
          </div>
        </div>
        
        <!-- 支付成功动画 -->
        <div class="success-animation" v-if="paymentSuccess">
          <div class="confetti-left"></div>
          <div class="confetti-right"></div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!paymentSuccess" @click="resumePayment">继续支付</el-button>
          <el-button v-if="!paymentSuccess" @click="cancelPaymentOrder">放弃支付</el-button>
          <el-button type="primary" @click="closePaymentResult">{{ paymentSuccess ? '完成' : '确认' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import { ShoppingCart, Present, Wallet, Loading, Timer, Check, CircleCheck, Warning, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { createOrderApi, queryOrderStatusApi, cancelOrderApi, getPackagesApi } from '@/api/payment';
import { getUserPackageApi } from '@/api/quota';
import { useRouter, useRoute } from 'vue-router';
import QRCode from 'qrcode';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 强制刷新标记
const forceReload = ref(false);

// 套餐配置 - 改为动态获取
const packages = ref({});
const packageTypes = ref([]);
const selectedPackageType = ref('');
const selectedPackage = ref(null);
const paymentMethod = ref(1); // 1: 微信支付, 2: 支付宝支付
const isSubmitting = ref(false);
const isLoadingPackages = ref(false);

// 支付相关状态
const paymentDialogVisible = ref(false);
const paymentResultDialogVisible = ref(false);
const paymentSuccess = ref(false);
const paymentQrCode = ref('');
const currentOrderNo = ref('');
const currentOrderAmount = ref(0);
const checkingPayment = ref(false);

// 支付倒计时
const paymentTimeRemaining = ref('30:00');
let paymentTimer = null;
let paymentStatusTimer = null;
let paymentTimeLeft = 30 * 60; // 30分钟，以秒为单位

const qrcodeContainer = ref(null);
const alipayFormContainer = ref(null);

// 根据选择的套餐类型获取对应的套餐列表
const packagesByType = computed(() => {
  return selectedPackageType.value ? packages.value[selectedPackageType.value] || [] : [];
});

// 监听路由参数变化，重新选择套餐
watch(
  () => route.query,
  async (newQuery) => {
    // 检查是否是支付回调
    if (newQuery.method === 'alipay.trade.page.pay.return' || newQuery.status === 'success') {
      // 支付回调处理会在onMounted中进行，这里不重复处理
      return;
    }

    // 处理套餐价格参数
    if (newQuery.price && packages.value && Object.keys(packages.value).length > 0) {
      // 设置强制刷新标记
      forceReload.value = true;
      
      // 匹配套餐
      await matchPackageFromUrlParams(newQuery);
    }
  },
  { deep: true }
);

// 从URL参数匹配套餐的函数
const matchPackageFromUrlParams = async (queryParams) => {
  if (!queryParams.price) return;
  
  const targetPrice = Number(queryParams.price);
  
  // 如果套餐数据尚未加载，先加载数据
  if (!packages.value || Object.keys(packages.value).length === 0) {
    await fetchPackages();
    if (!packages.value || Object.keys(packages.value).length === 0) {
      return;
    }
  }
  
  // 检查所有套餐类型，找到匹配价格的套餐
  let foundMatchingPackage = false;
  
  // 如果URL中包含套餐类型，优先匹配该类型下的套餐
  if (queryParams.packageType) {
    const urlPackageType = queryParams.packageType;
    // 尝试找到匹配或包含关系的套餐类型
    const matchingTypes = packageTypes.value.filter(type => 
      type === urlPackageType || 
      type.toLowerCase().includes(urlPackageType.toLowerCase()) || 
      urlPackageType.toLowerCase().includes(type.toLowerCase())
    );
    
    if (matchingTypes.length > 0) {
      selectedPackageType.value = matchingTypes[0];
      
      // 在该类型下查找匹配价格的套餐
      const typePackages = packages.value[matchingTypes[0]] || [];
      const matchPackage = typePackages.find(pkg => Math.abs(pkg.price - targetPrice) < 0.1); // 允许0.1元误差
      if (matchPackage) {
        selectedPackage.value = matchPackage;
        foundMatchingPackage = true;
      }
    }
  }
  
  // 如果未找到匹配的套餐，在所有类型中搜索
  if (!foundMatchingPackage) {
    for (const type of packageTypes.value) {
      const typePackages = packages.value[type] || [];
      const matchPackage = typePackages.find(pkg => Math.abs(pkg.price - targetPrice) < 0.1); // 允许0.1元误差
      if (matchPackage) {
        selectedPackageType.value = type;
        selectedPackage.value = matchPackage;
        foundMatchingPackage = true;
        break;
      }
    }
  }
  
  // 如果仍未找到匹配的套餐，选择价格最接近的
  if (!foundMatchingPackage) {
    let closestPackage = null;
    let minPriceDiff = Infinity;
    let closestType = null;
    
    for (const type of packageTypes.value) {
      const typePackages = packages.value[type] || [];
      for (const pkg of typePackages) {
        const priceDiff = Math.abs(pkg.price - targetPrice);
        if (priceDiff < minPriceDiff) {
          minPriceDiff = priceDiff;
          closestPackage = pkg;
          closestType = type;
        }
      }
    }
    
    if (closestPackage) {
      selectedPackageType.value = closestType;
      selectedPackage.value = closestPackage;
    } else {
      // 如果没有找到匹配的套餐，创建一个虚拟套餐对象防止null错误
      selectedPackage.value = {
        price: targetPrice,
        duration: '未知', 
        points: 0,
        title: '自定义套餐'
      };
    }
  }
  
  // 使用nextTick确保DOM更新后再滚动到对应套餐
  return new Promise(resolve => {
    nextTick(() => {
      setTimeout(() => {
        try {
          // 查找当前选中套餐的索引
          const currentType = selectedPackageType.value;
          const currentPackages = packages.value[currentType] || [];
          const selectedIndex = currentPackages.findIndex(pkg => 
            selectedPackage.value && pkg.price === selectedPackage.value.price
          );
          
          if (selectedIndex !== -1) {
            const packageCards = document.querySelectorAll('.package-card');
            
            if (packageCards && packageCards[selectedIndex]) {
              packageCards[selectedIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
              
              // 添加高亮效果
              packageCards.forEach(card => card.classList.remove('active'));
              packageCards[selectedIndex].classList.add('active');
              
              // 应用强调动画
              packageCards[selectedIndex].style.animation = 'none';
              setTimeout(() => {
                packageCards[selectedIndex].style.animation = 'highlight-card 1s ease-in-out';
              }, 10);
            }
          }
          resolve();
        } catch (e) {
          resolve();
        }
      }, 500);
    });
  });
};

// 获取套餐信息
const fetchPackages = async () => {
  isLoadingPackages.value = true;
  try {
    const response = await getPackagesApi();
    if (response.data.code === 200) {
      // 保存原始数据
      packages.value = response.data.data;
      
      // 获取所有套餐类型
      packageTypes.value = Object.keys(response.data.data);
      
      // 默认选择第一个类型
      if (packageTypes.value.length > 0) {
        selectedPackageType.value = packageTypes.value[0];
        
        // 检查URL参数，如果有价格参数，直接跳转到对应套餐
        if (route.query.price && Number(route.query.price) > 0) {
          matchPackageFromUrlParams(route.query);
        } else {
          // 选择第一个套餐
          const currentPackages = packagesByType.value;
          if (currentPackages && currentPackages.length > 0) {
            selectedPackage.value = currentPackages[0];
          }
        }
      }
    } else {
      ElMessage.warning('获取套餐信息失败');
    }
  } catch (error) {
    // console.error('获取套餐信息失败', error);
    ElMessage.warning('获取套餐信息失败');
  } finally {
    isLoadingPackages.value = false;
  }
};

// 重置已选套餐
const resetPackage = () => {
  selectedPackage.value = null;
  
  // 获取当前类型的套餐列表
  const currentPackages = packagesByType.value;
  if (currentPackages && currentPackages.length > 0) {
    selectedPackage.value = currentPackages[0];
  }
};

// 选择套餐
const selectPackage = (pkg) => {
  selectedPackage.value = pkg;
};

// 选择支付方式
const selectPaymentMethod = (method) => {
  paymentMethod.value = method;
};

// 创建支付订单
const createPaymentOrder = async () => {
  if (!selectedPackage.value) {
    ElMessage.warning('请先选择套餐');
    return;
  }

  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式');
    return;
  }

  try {
    isSubmitting.value = true;

    // 获取userId（从userStore中获取，如果登录了的话）
    const userId = userStore.userInfo?.id || null;
    
    const orderData = {
      amount: selectedPackage.value.price,
      paymentType: paymentMethod.value,
      packageType: getPackageTypeText(),
      packagePoints: selectedPackage.value.points,
      packageDuration: selectedPackage.value.duration,
      userId: userId // 传递userId，如果未登录则为null
    };

    const response = await createOrderApi(orderData);
    if (response.data.code === 200) {
      const orderInfo = response.data.data;
      
      // 保存订单信息
      currentOrderNo.value = orderInfo.orderNo;
      currentOrderAmount.value = orderInfo.amount;
      paymentQrCode.value = orderInfo.qrCodeUrl;
      
      // 根据支付方式处理不同的支付流程
      if (paymentMethod.value === 1) {
        // 微信支付 - 显示扫码支付弹窗
      paymentDialogVisible.value = true;
      
      // 开始支付倒计时
      startPaymentTimer();
      
      // 自动轮询支付状态
      startStatusPolling();
      } else if (paymentMethod.value === 2) {
        // 支付宝 - 直接跳转到支付页面，不显示弹窗
        const alipayWindow = window.open('', '_blank');
        if (alipayWindow) {
          alipayWindow.document.write(paymentQrCode.value);
          alipayWindow.document.close();
          
          // 开始支付倒计时和状态轮询（后台运行，不显示弹窗）
          startPaymentTimer();
          startStatusPolling();
          
          ElMessage.success('已跳转到支付宝支付页面，支付完成后将自动处理订单');
        } else {
          // 如果无法打开新窗口，则显示弹窗让用户手动操作
          paymentDialogVisible.value = true;
          ElMessage.warning('浏览器阻止了弹出窗口，请点击"去支付"按钮手动支付');
          
          // 开始支付倒计时
          startPaymentTimer();
          
          // 自动轮询支付状态
          startStatusPolling();
        }
      }
    } else {
      ElMessage.error(response.data.msg || '创建订单失败');
    }
  } catch (error) {
    // console.error('创建支付订单失败', error);
    ElMessage.error('创建支付订单失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};

// 获取套餐类型文本
const getPackageTypeText = () => {
  return selectedPackageType.value || '套餐';
};

// 开始支付倒计时
const startPaymentTimer = () => {
  clearInterval(paymentTimer);
  paymentTimeLeft = 30 * 60; // 30分钟
  updatePaymentTimeDisplay();
  
  paymentTimer = setInterval(() => {
    paymentTimeLeft--;
    updatePaymentTimeDisplay();
    
    if (paymentTimeLeft <= 0) {
      clearInterval(paymentTimer);
      // 订单超时，取消订单
      cancelPaymentOrder();
      ElMessage.warning('支付超时，订单已取消');
      paymentDialogVisible.value = false;
    }
  }, 1000);
};

// 更新支付倒计时显示
const updatePaymentTimeDisplay = () => {
  const minutes = Math.floor(paymentTimeLeft / 60);
  const seconds = paymentTimeLeft % 60;
  paymentTimeRemaining.value = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

// 开始轮询支付状态
const startStatusPolling = () => {
  clearInterval(paymentStatusTimer);
  
  // 每10秒查询一次支付状态
  paymentStatusTimer = setInterval(async () => {
    await checkPaymentStatus(true);
  }, 10000);
};

// 停止轮询支付状态
const stopStatusPolling = () => {
  clearInterval(paymentStatusTimer);
};

// 查询支付状态
const checkPaymentStatus = async (silent = false) => {
  if (!currentOrderNo.value) return;
  
  try {
    checkingPayment.value = true;
    
    const response = await queryOrderStatusApi(currentOrderNo.value);
    if (response.data.code === 200) {
      const orderInfo = response.data.data;
      
      // 已支付
      if (orderInfo.status === 1) {
        stopStatusPolling();
        clearInterval(paymentTimer);
        
        paymentSuccess.value = true;
        paymentDialogVisible.value = false;
        paymentResultDialogVisible.value = true;
        
        // 支付成功时刷新用户会员信息
        try {
          const packageResponse = await getUserPackageApi();
          if (packageResponse.data.code === 200) {
            const packageData = packageResponse.data.data;
            
            // 更新用户的会员信息
            const updatedMembershipInfo = {
              packageType: packageData.packageType,
              remainingQuota: Math.max(0, packageData.totalQuota - packageData.usedQuota),
              remainingDays: Math.floor(Math.max(0, (new Date(packageData.endTime) - new Date()) / 86400000))
            };
            
            // 更新store中的会员信息
            userStore.updateMembership(updatedMembershipInfo);
          }
        } catch (error) {
          // console.error('刷新会员信息失败', error);
        }
        
        ElMessage.success('支付成功！');
        return true;
      }
      
      // 支付失败或已取消
      if (orderInfo.status === 2 || orderInfo.status === 3) {
        stopStatusPolling();
        clearInterval(paymentTimer);
        
        if (!silent) {
          ElMessage.error('支付失败，请重新尝试');
        }
        
        if (orderInfo.status === 3) {
          paymentDialogVisible.value = false;
        }
        
        return false;
      }
      
      // 未支付，继续等待
      if (orderInfo.status === 0 && !silent) {
        ElMessage.info('暂未检测到支付完成，请确认是否已支付');
        
        // 显示查询结果弹窗
        paymentSuccess.value = false;
        paymentDialogVisible.value = false;
        paymentResultDialogVisible.value = true;
      }
      
      return false;
    } else {
      if (!silent) {
        ElMessage.error(response.data.msg || '查询支付状态失败');
      }
      return false;
    }
  } catch (error) {
    // console.error('查询支付状态失败', error);
    if (!silent) {
      ElMessage.error('查询支付状态失败，请重试');
    }
    return false;
  } finally {
    checkingPayment.value = false;
  }
};

// 取消支付
const cancelPayment = async () => {
  const confirmed = await ElMessageBox.confirm('确定要取消支付吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '继续支付',
    type: 'warning'
  }).catch(() => false);
  
  if (confirmed) {
    cancelPaymentOrder();
    paymentDialogVisible.value = false;
  }
};

// 取消支付订单
const cancelPaymentOrder = async () => {
  if (!currentOrderNo.value) return;
  
  try {
    stopStatusPolling();
    clearInterval(paymentTimer);
    
    await cancelOrderApi(currentOrderNo.value);
    ElMessage.info('已取消支付');
  } catch (error) {
    // console.error('取消订单失败', error);
  }
};

// 继续支付
const resumePayment = () => {
  paymentResultDialogVisible.value = false;
  paymentDialogVisible.value = true;
};

// 关闭支付结果弹窗
const closePaymentResult = async () => {
  paymentResultDialogVisible.value = false;
  
  if (paymentSuccess.value) {
    try {
      // 在支付成功后立即刷新用户会员信息
      const response = await getUserPackageApi();
      if (response.data.code === 200) {
        const packageData = response.data.data;
        
        // 更新用户的会员信息
        const updatedMembershipInfo = {
          packageType: packageData.packageType,
          remainingQuota: Math.max(0, packageData.totalQuota - packageData.usedQuota),
          remainingDays: Math.floor(Math.max(0, (new Date(packageData.endTime) - new Date()) / 86400000))
        };
        
        // 更新store中的会员信息
        userStore.updateMembership(updatedMembershipInfo);
        
        ElMessage.success('会员信息已更新');
      }
    } catch (error) {
      // console.error('刷新会员信息失败', error);
    }
    
    // 支付成功后，跳转到套餐页面
    router.push('/main/quota');
  }
};

// 监听paymentQrCode和弹窗状态，生成二维码
watch([paymentQrCode, paymentDialogVisible], async () => {
  if (paymentQrCode.value && paymentDialogVisible.value) {
    await nextTick();
    generateQrCode();
  }
});

// 监听套餐类型变化，尝试重新匹配URL参数中的套餐
watch(selectedPackageType, (newType) => {
  // 检查URL中是否有套餐参数
  if (route.query.price && Number(route.query.price) > 0 && packages.value && Object.keys(packages.value).length > 0) {
    const targetPrice = Number(route.query.price);
    
    // 获取当前类型下的套餐列表
    const packageList = packages.value[newType] || [];
    
    // 查找匹配价格的套餐
    const matchedPackage = packageList.find(pkg => pkg.price === targetPrice);
    if (matchedPackage) {
      selectedPackage.value = matchedPackage;
      
      // 添加延时，确保DOM更新后再滚动
      setTimeout(() => {
        try {
          const packageCards = document.querySelectorAll('.package-card');
          const index = packageList.findIndex(pkg => pkg.price === targetPrice);
          if (packageCards && packageCards[index]) {
            packageCards[index].scrollIntoView({ behavior: 'smooth', block: 'center' });
            
            // 添加高亮效果
            packageCards.forEach(card => card.classList.remove('active'));
            packageCards[index].classList.add('active');
            
            // 应用强调动画
            packageCards[index].style.animation = 'none';
            setTimeout(() => {
              packageCards[index].style.animation = 'highlight-card 1s ease-in-out';
            }, 10);
          }
        } catch (e) {
          // console.error('滚动到套餐位置失败:', e);
        }
      }, 300);
    } else {
      // console.log('未找到价格匹配的套餐');
    }
  }
});

// 使用qrcode库生成二维码
const generateQrCode = async () => {
  if (!qrcodeContainer.value && !alipayFormContainer.value) return;
  
  if (paymentMethod.value === 1) {
    // 微信支付 - 生成二维码
  if (!qrcodeContainer.value) return;
  
  // 清空容器
  qrcodeContainer.value.innerHTML = '';
  
  try {
    // 创建一个canvas元素
    const canvas = document.createElement('canvas');
    qrcodeContainer.value.appendChild(canvas);
    
    // 生成二维码
    await QRCode.toCanvas(canvas, paymentQrCode.value, {
      width: 200,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#ffffff'
      }
    });
  } catch (error) {
    // 如果Canvas方式失败，使用图片URL作为备选方案
    const img = document.createElement('img');
    const qrApiUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(paymentQrCode.value)}`;
    img.src = qrApiUrl;
    img.alt = "支付二维码";
    img.style.width = "200px";
    img.style.height = "200px";
    qrcodeContainer.value.appendChild(img);
    }
  } else if (paymentMethod.value === 2) {
    // 支付宝支付 - 处理HTML表单
    if (!alipayFormContainer.value) return;
    
    // 清空容器
    alipayFormContainer.value.innerHTML = '';
    
    try {
      // 直接将返回的HTML插入到容器中
      alipayFormContainer.value.innerHTML = paymentQrCode.value;
      
      // 自动提交表单
      const form = alipayFormContainer.value.querySelector('form');
      if (form) {
        setTimeout(() => {
          window.open('', '_blank');
          form.target = '_blank';
          form.submit();
        }, 100);
      } else {
        ElMessage.error('生成支付表单失败，请重试');
      }
    } catch (error) {
      // console.error('处理支付宝表单失败', error);
      ElMessage.error('处理支付表单失败，请重试');
    }
  }
};

// 刷新套餐数据
const refreshPackages = async () => {
  if (isLoadingPackages.value) return;
  
  // 重置状态
  selectedPackage.value = null;
  
  // 获取当前URL参数
  const urlParams = { ...route.query };
  
  // 重新加载套餐数据
  await fetchPackages();
  
  // 如果有URL参数，重新匹配套餐
  if (urlParams.price) {
    nextTick(() => {
      matchPackageFromUrlParams(urlParams);
    });
  }
};

// 组件挂载
onMounted(async () => {
  // console.log('组件挂载，准备获取套餐数据');
  // console.log('当前路由参数:', route.query);
  
  // 强制刷新机制：当从别的页面跳转到充值页面时，确保数据重新加载
  if (document.referrer && !document.referrer.includes('/recharge')) {
    // console.log('从其他页面跳转过来的，强制重新加载数据');
    // 重置状态
    packages.value = {};
    selectedPackage.value = null;
    packageTypes.value = [];
    
    // 延迟执行刷新，确保组件完全挂载
    setTimeout(() => {
      refreshPackages();
    }, 100);
  } else {
    // 正常加载
    await fetchPackages();
  }
  
  // 检查是否是支付宝回调
  if (route.query.method === 'alipay.trade.page.pay.return') {
    // console.log('检测到支付宝回调:', route.query);
    
    // 获取订单金额
    const totalAmount = parseFloat(route.query.total_amount || '0');
    // console.log('实际支付金额:', totalAmount);
    
    try {
      // 先确保套餐数据已加载
      if (!packages.value || Object.keys(packages.value).length === 0) {
        await fetchPackages();
      }
      
      // 尝试匹配实际支付的套餐
      await matchPackageFromUrlParams({ price: totalAmount });
      
      // 根据实际支付金额创建套餐信息
      let packageInfo;
      
      // 如果找到了匹配的套餐，使用它
      if (selectedPackage.value && Math.abs(selectedPackage.value.price - totalAmount) < 0.1) {
        packageInfo = { ...selectedPackage.value };
      } else {
        // 否则搜索所有套餐，找出最接近的
        let bestMatch = null;
        let minDiff = Infinity;
        
        for (const type in packages.value) {
          for (const pkg of packages.value[type]) {
            const diff = Math.abs(pkg.price - totalAmount);
            if (diff < minDiff) {
              minDiff = diff;
              bestMatch = pkg;
              selectedPackageType.value = type;
            }
          }
        }
        
        // 如果找到了较接近的套餐
        if (bestMatch && minDiff < 1) {
          packageInfo = { ...bestMatch };
        } else {
          // 如果支付的是0.01元测试金额，显示短期测试套餐
          if (totalAmount <= 0.01) {
            packageInfo = {
              duration: '1天',
              price: totalAmount,
              points: 100,
              title: '测试套餐'
            };
            selectedPackageType.value = '测试套餐';
          } else {
            // 创建一个基于金额的自定义套餐
            packageInfo = {
              duration: Math.ceil(totalAmount / 2) + '天', // 粗略估计：2元1天
              price: totalAmount,
              points: Math.ceil(totalAmount * 1000),
              title: '自定义套餐'
            };
            selectedPackageType.value = '标准套餐';
          }
        }
      }
      
      // console.log('匹配到的套餐信息:', packageInfo);
      
      // 设置支付成功信息
      paymentSuccess.value = true;
      
      // 更新selectedPackage为实际支付的套餐
      selectedPackage.value = packageInfo;
      
      // 显示支付结果弹窗
      nextTick(() => {
        paymentResultDialogVisible.value = true;
        ElMessage.success('支付成功！');
      });
      
      // 刷新用户会员信息
      try {
        const response = await getUserPackageApi();
        if (response.data.code === 200) {
          const packageData = response.data.data;
          
          // 更新用户的会员信息
          const updatedMembershipInfo = {
            packageType: packageData.packageType,
            remainingQuota: Math.max(0, packageData.totalQuota - packageData.usedQuota),
            remainingDays: Math.floor(Math.max(0, (new Date(packageData.endTime) - new Date()) / 86400000))
          };
          
          // 更新store中的会员信息
          userStore.updateMembership(updatedMembershipInfo);
        }
      } catch (error) {
        // console.error('刷新会员信息失败', error);
      }
    } catch (error) {
      // console.error('处理支付回调失败:', error);
      ElMessage.warning('处理支付结果时出现错误');
    }
  }
  // 检查URL中是否有支付状态参数
  else if (route.query.status === 'success') {
    // 获取订单金额
    const totalAmount = parseFloat(route.query.total_amount || '0');
    
    // 如果有金额参数，尝试匹配套餐
    if (totalAmount > 0) {
      try {
        // 确保套餐数据已加载
        if (!packages.value || Object.keys(packages.value).length === 0) {
          await fetchPackages();
        }
        
        // 尝试匹配实际支付的套餐
        await matchPackageFromUrlParams({ price: totalAmount });
        
        // 如果没有匹配到合适的套餐，创建临时套餐
        if (!selectedPackage.value || Math.abs(selectedPackage.value.price - totalAmount) > 0.1) {
          // 如果支付的是测试金额
          if (totalAmount <= 0.01) {
            selectedPackage.value = {
              duration: '1天',
              price: totalAmount,
              points: 100,
              title: '测试套餐'
            };
            selectedPackageType.value = '测试套餐';
          } else {
            // 创建自定义套餐
            selectedPackage.value = {
              duration: Math.ceil(totalAmount / 2) + '天',
              price: totalAmount,
              points: Math.ceil(totalAmount * 1000),
              title: '自定义套餐'
            };
            selectedPackageType.value = '标准套餐';
          }
        }
      } catch (error) {
        // console.error('处理支付参数失败', error);
      }
    }
    
    // 显示支付成功弹窗
    paymentSuccess.value = true;
    paymentResultDialogVisible.value = true;
    ElMessage.success('支付已成功处理！');
    
    // 刷新用户会员信息
    try {
      const response = await getUserPackageApi();
      if (response.data.code === 200) {
        const packageData = response.data.data;
        
        // 更新用户的会员信息
        const updatedMembershipInfo = {
          packageType: packageData.packageType,
          remainingQuota: Math.max(0, packageData.totalQuota - packageData.usedQuota),
          remainingDays: Math.floor(Math.max(0, (new Date(packageData.endTime) - new Date()) / 86400000))
        };
        
        // 更新store中的会员信息
        userStore.updateMembership(updatedMembershipInfo);
      }
    } catch (error) {
      // console.error('刷新会员信息失败', error);
    }
    
    // 清除URL中的支付状态参数，避免刷新页面时重复显示
    const query = { ...route.query };
    delete query.status;
    router.replace({ query });
  }
});

// 组件销毁前清理定时器
onBeforeUnmount(() => {
  stopStatusPolling();
  clearInterval(paymentTimer);
});
</script>

<style lang="scss" scoped>
.recharge-container {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  
  .package-select, .payment-method {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    
    :deep(.el-card__header) {
      padding: 20px 24px;
      border-bottom: 1px solid #e6e8eb;
    }
  }
  
  .card-header {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .header-icon {
      font-size: 24px;
      color: #1a73e8;
    }
    
    span {
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
      flex-grow: 1;
    }
    
    .header-actions {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
  
  .package-options {
    padding: 20px;
    
    .package-usage-info {
      margin-bottom: 20px;
      
      .usage-info-content {
        font-size: 14px;
        line-height: 1.5;
        
        p {
          margin: 0;
        }
      }
    }
    
    .package-types {
      margin-bottom: 20px;
    }
    
    .loading-packages {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 40px 0;
      gap: 16px;
      
      .loading-icon {
        font-size: 40px;
        color: #1a73e8;
        animation: rotate 2s linear infinite;
      }
      
      span {
        font-size: 16px;
        color: #64748b;
      }
    }
    
    .packages-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
    }
    
    .package-card {
      position: relative;
      border: 1px solid #e6e8eb;
      border-radius: 12px;
      padding: 20px;
      transition: all 0.3s ease;
      cursor: pointer;
      
      &.active {
        border-color: #1a73e8;
        box-shadow: 0 4px 16px rgba(26, 115, 232, 0.15);
        animation: highlight-card 1s ease-in-out;
      }
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
      }
      
      .recommended {
        position: absolute;
        top: -12px;
        right: 20px;
        background-color: #f56c6c;
        color: white;
        padding: 2px 10px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: bold;
      }
      
      .package-header {
        display: flex;
        flex-direction: column;
        margin-bottom: 16px;
        
        .title {
          font-size: 18px;
          font-weight: 600;
          color: #1f2937;
        }
        
        .duration {
          font-size: 14px;
          color: #64748b;
          margin-top: 4px;
        }
      }
      
      .package-price {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 16px;
        
        .price-amount {
          font-size: 24px;
          font-weight: 700;
          color: #f56c6c;
        }
        
        .original-price {
          font-size: 14px;
          color: #a0aec0;
          text-decoration: line-through;
        }
      }
      
      .package-details {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .detail-item {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .detail-icon {
            color: #1a73e8;
          }
        }
        
        .features {
          margin-top: 8px;
          display: flex;
          flex-direction: column;
          gap: 8px;
          
          .feature-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #64748b;
            
            .feature-icon {
              color: #10b981;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
  
  .payment-methods {
    padding: 20px;
    
    .method-options {
      display: flex;
      gap: 20px;
      flex-wrap: wrap;
      
      .method-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 150px;
        height: 120px;
        border: 1px solid #e6e8eb;
        border-radius: 12px;
        padding: 16px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &.active {
          border-color: #1a73e8;
          background-color: rgba(26, 115, 232, 0.05);
        }
        
        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        }
        
        .method-icon {
          width: 60px;
          height: 60px;
          object-fit: contain;
          margin-bottom: 12px;
        }
        
        .method-name {
          font-size: 16px;
          font-weight: 500;
        }
      }
    }
  }
  
  .payment-action {
    display: flex;
    justify-content: center;
    padding: 20px;
    
    .el-button {
      min-width: 200px;
    }
  }
  
  .payment-dialog {
    :deep(.el-dialog__header) {
      padding: 16px 20px;
      margin-right: 0;
      text-align: center;
      border-bottom: 1px solid #ebeef5;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    :deep(.el-dialog__body) {
      padding: 20px;
    }
  }
  
  .payment-dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .payment-info {
      width: 100%;
      
      .order-details {
        background-color: #f8fafc;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid #ebeef5;
        
        .order-info-item {
          display: flex;
          margin-bottom: 10px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .label {
            width: 80px;
            color: #64748b;
            font-size: 14px;
          }
          
          .value {
            flex: 1;
            font-weight: 500;
            color: #1f2937;
            font-size: 14px;
            word-break: break-all;
            
            &.price {
              color: #f56c6c;
              font-weight: 600;
            }
          }
          
          &.payment-countdown {
            display: flex;
            align-items: center;
            margin-top: 5px;
            padding-top: 10px;
            border-top: 1px dashed #e2e8f0;
            color: #f56c6c;
            
            .el-icon {
              margin-right: 5px;
            }
          }
        }
      }
    
    .qrcode-container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 220px;
      height: 220px;
        margin: 15px auto 25px;
      border: 1px solid #e6e8eb;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        background-color: #ffffff;
      
      .qrcode-image {
        width: 200px;
        height: 200px;
        display: flex;
        justify-content: center;
        align-items: center;
          
          canvas {
            border-radius: 4px;
          }
      }
      
      .loading-qrcode {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
        color: #64748b;
        
        .loading-icon {
          font-size: 40px;
          animation: rotate 2s linear infinite;
        }
      }
    }
    
      .payment-actions {
        display: flex;
        justify-content: center;
        gap: 15px;
        
        .el-button {
          min-width: 100px;
        }
      }
    }
  }
  
  .payment-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 0;
    position: relative;
    overflow: hidden;
    
    .result-icon {
      margin-bottom: 15px;
      
      .status-icon {
        font-size: 50px;
      }
      
      .success-icon {
        color: #10b981;
      }
      
      .waiting-icon {
        color: #f59e0b;
      }
    }
    
    .result-message {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 8px;
      text-align: center;
    }
    
    .result-detail {
      color: #64748b;
      text-align: center;
      margin-bottom: 15px;
    }
    
    .package-details-success {
      background-color: #f8fafc;
      border-radius: 8px;
      width: 100%;
      padding: 15px;
      margin-top: 5px;
      border: 1px solid #e2e8f0;
      
      .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        font-size: 14px;
        
        &:last-child {
          margin-bottom: 0;
          padding-top: 5px;
          border-top: 1px dashed #e2e8f0;
        }
        
        .detail-label {
          color: #64748b;
        }
        
        .detail-value {
          font-weight: 500;
          color: #334155;
          
          &.points {
            color: #10b981;
          }
          
          &.price {
            color: #f43f5e;
            font-weight: 600;
          }
        }
      }
    }
    
    // 成功动画样式
    .success-animation {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      pointer-events: none;
      z-index: -1;
      
      .confetti-left, .confetti-right {
        position: absolute;
        width: 100px;
        height: 100px;
        opacity: 0;
        animation: confetti-burst 1s ease-out forwards;
        background-image: radial-gradient(circle, 
                          #10b981 10%, 
                          #3b82f6 25%, 
                          #f43f5e 50%, 
                          #f59e0b 75%);
        border-radius: 50%;
        filter: blur(20px);
      }
      
      .confetti-left {
        top: -20px;
        left: -20px;
        animation-delay: 0.2s;
      }
      
      .confetti-right {
        bottom: -20px;
        right: -20px;
        animation-delay: 0.4s;
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 添加移动端适配
@media (max-width: 768px) {
  .recharge-container {
    .packages-grid {
      grid-template-columns: 1fr;
    }
    
    .method-options {
      justify-content: center;
    }
  }
}

// 添加高亮动画
@keyframes highlight-card {
  0% {
    transform: translateY(0);
    box-shadow: 0 4px 16px rgba(26, 115, 232, 0.15);
  }
  25% {
    transform: translateY(-8px);
    box-shadow: 0 8px 24px rgba(26, 115, 232, 0.2);
  }
  50% {
    transform: translateY(-4px);
    box-shadow: 0 6px 20px rgba(26, 115, 232, 0.18);
  }
  75% {
    transform: translateY(-6px);
    box-shadow: 0 7px 22px rgba(26, 115, 232, 0.19);
  }
  100% {
    transform: translateY(-4px);
    box-shadow: 0 6px 20px rgba(26, 115, 232, 0.15);
  }
}

// 动画关键帧
@keyframes confetti-burst {
  0% {
    transform: scale(0);
    opacity: 0.8;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}

.dialog-footer {
  padding-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.alipay-form-container {
  width: 100%;
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
}
</style> 